﻿using System.IO;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;
using InnovTech.Util.IO;

namespace InnovTech.Util.Crypto
{
    public static class CryptoUtil
    {
        public static MemoryStream Crypt(Stream input, ICryptoTransform transform)
        {
            MemoryStream output = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(output, transform, CryptoStreamMode.Write);
            input.Position = StreamUtil.Reset(input);
            byte[] bytes;
            using (MemoryStream mem = new MemoryStream())
            {
                input.CopyTo(mem);
                bytes = mem.ToArray();
                mem.Close();
            }

            cryptoStream.Write(bytes, 0, bytes.Length);
            cryptoStream.FlushFinalBlock();
            return output;
        }

        public static MemoryStream Encrypt(object obj, ICryptoTransform transform)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(stream, obj);
                stream.Position = 0;
                MemoryStream mem = Crypt(stream, transform);
                stream.Close();
                return mem;
            }
        }

        public static object Decrypt(Stream stream, ICryptoTransform transform)
        {
            StreamUtil.Reset(stream);
            using (MemoryStream mem = Crypt(stream, transform))
            {
                mem.Position = 0;

                BinaryFormatter bf = new BinaryFormatter();
                object obj = bf.Deserialize(mem);

                mem.Close();
                return obj;
            }
        }


        
    }
}
